﻿Imports System.Data
Imports System.Data.OleDb

Partial Class CustomerInfo
    Inherits System.Web.UI.UserControl
    Private pMode As DetailsViewMode
    Public Property Mode() As DetailsViewMode
        Get
            Return pMode
        End Get
        Set(ByVal value As DetailsViewMode)
            pMode = value
        End Set
    End Property
    Private pShowButton As Boolean = True
    Public Property ShowButton() As Boolean
        Get
            Return pShowButton
        End Get
        Set(ByVal value As Boolean)
            pShowButton = value
        End Set
    End Property
    Private pRedirect As Boolean = True
    Public Property Redirect() As Boolean
        Get
            Return pRedirect
        End Get
        Set(ByVal value As Boolean)
            pRedirect = value
        End Set
    End Property
    Public Sub Validate()
        Page.Validate()
    End Sub
    Public Sub Save()
        If Page.IsValid Then
            If pMode = DetailsViewMode.Edit Then
                dvUserData.UpdateItem(True)
                dvCustomerData.UpdateItem(True)
                lblError.Text = "Profile was updated successfully."
                'If UserName is in Viewstate during update it means, username was changed.
                If Not IsNothing(ViewState("UserName")) Then
                    Dim user As New User(ViewState("UserName"))
                    user.Login()
                End If
            ElseIf pMode = DetailsViewMode.Insert Then
                'Save UserData first, then get ID to add to Customer Data
                dvUserData.InsertItem(True)
                If lblError.Text = String.Empty Then
                    dvCustomerData.InsertItem(True)
                End If
                If Not IsNothing(ViewState("UserName")) AndAlso lblError.Text = String.Empty Then
                    Dim user As New User(ViewState("UserName"))
                    user.Login()
                    If pRedirect Then
                        Response.Redirect("MyProfile.aspx")
                    End If
                End If
            End If
        End If
    End Sub
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsNothing(Session("UserObject")) Then
            lblCustomerID.Text = CType(Session("UserObject"), User).CustomerID
            lblUserID.Text = CType(Session("UserObject"), User).UserID
        End If
        If IsNothing(pMode) Then
            pMode = DetailsViewMode.Edit
        End If
        dvCustomerData.ChangeMode(pMode)
        dvUserData.ChangeMode(pMode)
        If pMode = DetailsViewMode.Edit Then
            btnSave.Text = "Update"
        ElseIf pMode = DetailsViewMode.Insert Then
            btnSave.Text = "Register"
        End If
        btnSave.Visible = pShowButton
    End Sub

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Save()
    End Sub

    Protected Sub dvUserData_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) Handles dvUserData.ItemInserted
        'For debug
        'For Each item As DictionaryEntry In e.Values
        '    lblError.Text += "<br/>" & item.Key.ToString & " " & Utility.GetValidString(item.Value)
        'Next
        'Get the ID for UserData
        e.KeepInInsertMode = True
        If Not e.Exception Is Nothing Then
            lblError.Text = "An error occured in the database: " & e.Exception.Message
            e.ExceptionHandled = True
        ElseIf e.AffectedRows = 0 Then
            lblError.Text = "A processing error occured, please try again."
            e.ExceptionHandled = True
        Else
            lblError.Text = String.Empty
            ViewState("UserName") = e.Values("UserName")
        End If

    End Sub

    Protected Sub UserData_Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles UserData.Inserted
        Dim query As String = "SELECT @@IDENTITY"
        Dim cmd As OleDbCommand = New OleDbCommand(query, CType(e.Command.Connection, OleDbConnection))
        Dim newid As Integer = CType(cmd.ExecuteScalar(), Integer)
        'Set the Customer Data field with new ID
        If newid > 0 Then
            ViewState("UserID") = newid
        End If
    End Sub

    Protected Sub dvCustomerData_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) Handles dvCustomerData.ItemInserted
        e.KeepInInsertMode = True
        If Not e.Exception Is Nothing Then
            lblError.Text = "An error occured in the database: " & e.Exception.Message
            e.ExceptionHandled = True
        ElseIf e.AffectedRows = 0 Then
            lblError.Text = "A processing error occured, please try again."
            e.ExceptionHandled = True
        Else
            lblError.Text = String.Empty
        End If
    End Sub

    Protected Sub StateChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim tmpddl As DropDownList = CType(sender, DropDownList)
        Dim lblCountry As Label = CType(dvCustomerData.FindControl("lblCountry"), Label)
        lblCountry.Text = Utility.GetCountry(tmpddl.SelectedValue)
    End Sub

    Protected Sub vldCustUserName_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
        If pMode = DetailsViewMode.Insert Then
            'Check that username is not taken in db
            Dim tmpUser As New User(args.Value)
            If tmpUser.isValid Then
                'UserName taken already
                args.IsValid = False
            Else
                args.IsValid = True
            End If
        ElseIf pMode = DetailsViewMode.Edit And args.Value.ToLower <> HttpContext.Current.User.Identity.Name.ToLower Then
            'User logged in is trying to update username
            Dim tmpUser As New User(args.Value)
            If tmpUser.isValid Then
                'UserName taken already
                args.IsValid = False
            Else
                args.IsValid = True
            End If
        End If
    End Sub

    Protected Sub dvUserData_ItemUpdated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewUpdatedEventArgs) Handles dvUserData.ItemUpdated
        e.KeepInEditMode = True
        If HttpContext.Current.User.Identity.IsAuthenticated AndAlso e.OldValues("UserName").ToString.ToLower <> e.NewValues("UserName").ToString.ToLower Then
            'UserName changed.. Setup viewstate item with new user for access later
            ViewState("UserName") = e.NewValues("UserName")
        End If
    End Sub

    Protected Sub dvUserData_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles dvUserData.ItemInserting
        'Encrypt Password before insert occurs
        e.Values("Password") = Security.Encrypt(e.Values("Password"))
    End Sub

    Protected Sub dvUserData_ItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewUpdateEventArgs) Handles dvUserData.ItemUpdating
        If e.OldValues("Password") <> e.NewValues("Password") Then
            e.NewValues("Password") = Security.Encrypt(e.NewValues("Password"))
        End If
    End Sub

    Protected Sub dvCustomerData_ItemUpdated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewUpdatedEventArgs) Handles dvCustomerData.ItemUpdated
        e.KeepInEditMode = True
    End Sub

    Protected Sub dvCustomerData_ItemInserting(sender As Object, e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles dvCustomerData.ItemInserting
        If Not IsNothing(ViewState("UserID")) Then
            e.Values.Add("UserID", ViewState("UserID"))
        Else
            e.Cancel = True
        End If

    End Sub
End Class
